package com.mioto.ld.module.file;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.text.StrBuilder;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import com.mioto.ld.exception.BasicException;
import com.mioto.ld.module.file.model.FileInfo;
import com.mioto.ld.result.SystemTip;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.Optional;

/**
 * @author admin
 * @date 2021-11-25 11:23
 */
@Component
public class FileHelper {
    @Value("${file.path}")
    private String filePath;

    /**
     * 创建文件目录
     * @return
     */
    public String createDirPath(){
        String dirPath = StrBuilder.create().append(filePath).append(StrUtil.SLASH).append(DateUtil.today()).toString();
        FileUtil.mkdir(dirPath);
        return dirPath;
    }

    /**
     * 创建文件名
     * @param fileName
     * @return
     */
    public String createNewFileName(String fileName){
        return StrBuilder.create()
                .append(DateUtil.format(new Date(), DatePattern.PURE_DATETIME_MS_FORMAT))
                .append(StrUtil.DOT)
                .append(getFileSuffix(fileName))
                .toString();
    }

    /**
     * 创建文件对象
     * @param realPath 文件完整路径
     * @param fileName 文件名
     * @return
     */
    public FileInfo buildFileInfo(String realPath, String fileName){
        FileInfo fileInfo = new FileInfo();
        fileInfo.setId(IdUtil.simpleUUID());
        fileInfo.setName(fileName);
        fileInfo.setFilePath(realPath.substring(filePath.length()));
        fileInfo.setCreateDate(new Date());
        return fileInfo;
    }

    /**
     * 获取文件名后缀
     * @param fileName
     * @return
     */
    public String getFileSuffix(String fileName){
        return Optional.ofNullable(fileName)
                .filter(name -> name.lastIndexOf(StrUtil.DOT) > 0 && name.lastIndexOf(StrUtil.DOT) < name.length())
                .map(name -> name.substring(name.lastIndexOf(StrUtil.DOT) + 1))
                .orElse(StrUtil.EMPTY);
    }

    /**
     * 文件下载
     * @param response
     * @param fileInfo
     */
    public void download(HttpServletResponse response, FileInfo fileInfo) {
        File file = new File(filePath + fileInfo.getFilePath());
        if (file.exists()) {
            OutputStream out = null;
            try {
                String contentType = "application/x-msdownload";
                response.setHeader("Content-Disposition", "attachment;filename=" + URLUtil.encode(fileInfo.getName()));
                response.setContentType(contentType);
                out = response.getOutputStream();
                FileUtil.writeToStream(file,out);
            } catch (IOException exception) {
                exception.printStackTrace();
            }finally {
                IoUtil.close(out);
            }
        }else {
            throw new BasicException(SystemTip.FILE_NOT_EXIST);
        }
    }
}
